<!--
 * @Descripttion: 编辑带客有礼
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2022-01-11 14:06:38
-->
<template>
  <div class="lb-edit-card">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <lb-classify-title title="基本信息"></lb-classify-title>
      <div style="height: 20px"></div>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="aForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="subForm.title"
            maxlength="40"
            show-word-limit
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="轮播图" prop="imgs">
          <lb-cover
            type="more"
            :fileList="subForm.imgs"
            @selectedFiles="selectedFiles($event, 'imgs')"
            @moveFiles="moveFiles($event, 'imgs')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 400</lb-tool-tips>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="form"
        :rules="timeRules"
        ref="timeForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="form.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="bForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="参与必授权">
          <el-checkbox-group v-model="checkList">
            <div
              v-for="(item, index) in authList"
              :key="index"
              :style="{
                display: 'inline-block',
                marginLeft: index === 0 ? 0 : '15px'
              }"
            >
              <el-checkbox :label="item.title"></el-checkbox>
              <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
            </div>
            <lb-tool-tips>选中后，需用户授权手机号才能领取此福利</lb-tool-tips>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="活动公司" prop="company">
          <el-cascader
            v-model="subForm.company"
            collapse-tags
            :options="base_company"
            @change="choiceAllCompanyItem"
            :props="{
              multiple: true,
              label: 'name',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>

        <div style="height: 20px"></div>
        <lb-classify-title title="新客户福利"></lb-classify-title>
        <div style="height: 20px"></div>
        <el-form-item label="福利券" prop="user_coupon_data">
          <el-input
            v-model="subForm.user_coupon_data"
            placeholder="请输入具体物品/金额"
            :maxLength="8"
          ></el-input>
          <lb-tool-tips
            >客户领取福利券后，到店消费可出示对应使用范围的福利券进行核销</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="福利有效期" prop="user_out_type">
          <el-radio-group v-model="subForm.user_out_type">
            <el-radio :label="1">指定日期</el-radio>
            <el-radio :label="2">有效天数</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="form"
        :rules="userOutTimeRules"
        ref="userOutTimeForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item
          label=""
          prop="user_out_time"
          v-if="subForm.user_out_type === 1"
        >
          <el-date-picker
            v-model="form.user_out_time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="userOutDayRules"
        ref="userOutDayForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item
          label
          prop="user_out_day"
          v-if="subForm.user_out_type === 2"
        >
          <el-input-number
            class="lb-input-number"
            v-model="subForm.user_out_day"
            :controls="false"
            :precision="0"
            :min="1"
            placeholder="请输入福利有效天数"
          ></el-input-number>
          <lb-tool-tips>福利券有效期自领取日算起</lb-tool-tips>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="cForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="使用范围" prop="user_coupon_range">
          <el-input
            v-model="subForm.user_coupon_range"
            placeholder="请输入使用范围"
          ></el-input>
        </el-form-item>
        <el-form-item label="福利券总数" prop="user_coupon_num">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.user_coupon_num"
            :controls="false"
            :precision="0"
            :min="1"
            placeholder="请输入福利券发放数量"
          ></el-input-number>
          <lb-tool-tips>整个平台可领取的福利券数量</lb-tool-tips>
        </el-form-item>

        <div style="height: 20px"></div>
        <lb-classify-title title="推荐人福利"></lb-classify-title>
        <div style="height: 20px"></div>
        <el-form-item label="福利券" prop="coupon_data">
          <el-input
            v-model="subForm.coupon_data"
            placeholder="请输入具体物品/金额"
          ></el-input>
          <lb-tool-tips
            >被推荐人领取新客户福利券并到店消费，店铺核销新客户福利券后可获得此券</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="福利有效期" prop="out_type">
          <el-radio-group v-model="subForm.out_type">
            <el-radio :label="1">指定日期</el-radio>
            <el-radio :label="2">有效天数</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="form"
        :rules="outTimeRules"
        ref="outTimeForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="" prop="out_time" v-if="subForm.out_type === 1">
          <el-date-picker
            v-model="form.out_time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="outDayRules"
        ref="outDayForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label prop="out_day" v-if="subForm.out_type === 2">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.out_day"
            :controls="false"
            :precision="0"
            :min="1"
            placeholder="请输入福利有效天数"
          ></el-input-number>
          <lb-tool-tips>福利券有效期自领取日算起</lb-tool-tips>
        </el-form-item>
      </el-form>

      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="dForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="使用范围" prop="coupon_range">
          <el-input
            v-model="subForm.coupon_range"
            placeholder="请输入使用范围"
          ></el-input>
        </el-form-item>
        <el-form-item label="可推荐人数" prop="coupon_num">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.coupon_num"
            :controls="false"
            :precision="0"
            :min="1"
            placeholder="请输入可推荐人数"
          ></el-input-number>
          <lb-tool-tips
            >限制用户可推荐此次活动的人数，所填人数不能大于福利券总数，用户分享给好友领取后减少一个推广名额</lb-tool-tips
          >
        </el-form-item>

        <div style="height: 20px"></div>
        <lb-classify-title title="内容设置"></lb-classify-title>
        <div style="height: 20px"></div>
        <el-form-item label="分享图片" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            fileType="image"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 600</lb-tool-tips>
        </el-form-item>
        <el-form-item label="活动描述" prop="content">
          <lb-ueditor v-model="subForm.content" :destroy="true"></lb-ueditor>
        </el-form-item>
        <el-form-item>
          <lb-button
            @click="submitFormInfo"
            type="primary"
            v-if="subForm.status_text !== 3"
            >{{ $t('action.save') }}</lb-button
          >
          <lb-button @click="goBack">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      navTitle: '',
      base_company: [],
      companyResult: [],
      checkList: [],
      authList: [
        {
          title: '手机号',
          key: 'is_mobile'
        }
      ],
      form: {
        time: [],
        out_time: [],
        user_out_time: [],
        copyCompanyId: []
      },
      timeRules: {
        time: { required: true, type: 'array', message: '请选择时间', trigger: 'change' }
      },
      outTimeRules: {
        out_time: { required: true, type: 'array', message: '请选择时间', trigger: 'change' }
      },
      userOutTimeRules: {
        user_out_time: { required: true, type: 'array', message: '请选择时间', trigger: 'change' }
      },
      outDayRules: {
        out_day: { required: true, type: 'number', message: '请输入福利有效天数', trigger: 'blur' }
      },
      userOutDayRules: {
        user_out_day: { required: true, type: 'number', message: '请输入福利有效天数', trigger: 'blur' }
      },
      // 基本信息
      subForm: {
        title: '',
        imgs: [],
        company: [],
        is_mobile: 0,
        start_time: '',
        end_time: '',
        coupon_data: '',
        coupon_start: '',
        coupon_end: '',
        coupon_range: '',
        coupon_num: '',
        out_type: 1,
        out_day: '',
        user_coupon_data: '',
        user_coupon_start: '',
        user_coupon_end: '',
        user_coupon_range: '',
        user_coupon_num: '',
        user_out_type: 1,
        user_out_day: '',
        cover: [],
        content: ''
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入标题', trigger: 'blur' },
        imgs: { required: true, type: 'array', message: '请上传图片', trigger: 'change' },
        company: { required: true, type: 'array', message: '请选择活动公司', trigger: 'change' },
        user_coupon_data: { required: true, type: 'string', message: '请输入具体物品/金额', trigger: 'blur' },
        user_out_type: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        user_coupon_range: { required: true, type: 'string', message: '请输入使用范围', trigger: 'blur' },
        user_coupon_num: { required: true, type: 'number', message: '请输入福利券发放数量', trigger: 'blur' },
        coupon_data: { required: true, type: 'string', message: '请输入具体物品/金额', trigger: 'blur' },
        out_type: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        coupon_range: { required: true, type: 'string', message: '请输入使用范围', trigger: 'blur' },
        coupon_num: { required: true, type: 'number', message: '请输入可推荐人数', trigger: 'blur' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: 'change' }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    await this.getBaseCompany()
    if (id) {
      this.id = id
      await this.getDetail(id)
    }
    this.navTitle = this.$t(!id ? 'menu.PresentAdd' : this.subForm.status_text === 3 ? 'menu.PresentView' : 'menu.PresentEdit')
  },
  methods: {
    async getDetail (id) {
      let { code, data } = await this.$api.presentActiveUpdate({ id })
      if (code !== 200) return
      data.imgs = data.imgs.map(item => {
        return { url: item }
      })
      data.cover = [{ url: data.cover }]
      let copyCompany = JSON.parse(JSON.stringify(data.company))
      let resCompany = copyCompany.length === this.companyResult.length ? [
        [0], ...copyCompany
      ] : copyCompany
      data.company = resCompany
      this.subForm = data
      let checkItem = []
      this.authList.map(item => {
        if (data[item.key] === 1) {
          checkItem.push(item.title)
        }
      })
      this.checkList = checkItem
      this.form.copyCompanyId = resCompany
      this.form.time = [this.handleMomentTime(data.start_time), this.handleMomentTime(data.end_time)]
      this.form.out_time = data.out_type === 1 ? [this.handleMomentTime(data.coupon_start), this.handleMomentTime(data.coupon_end)] : []
      this.form.user_out_time = data.user_out_type === 1 ? [this.handleMomentTime(data.user_coupon_start), this.handleMomentTime(data.user_coupon_end)] : []
    },
    async getBaseCompany () {
      // 基本信息验证
      let { data: company } = await this.$api.getBaseCompany()
      this.handleCompanyOptions(company)
      company.length &&
        company.unshift({
          id: 0,
          name: '全选'
        })
      this.base_company = company
    },
    handleCompanyOptions (data, arr = []) {
      for (let i = 0, len = data.length; i < len; i++) {
        let newArr = JSON.parse(JSON.stringify(arr))
        newArr.push(data[i].id)
        this.companyResult.push(JSON.parse(JSON.stringify(newArr)))
        if (data[i].children && data[i].children.length) {
          this.handleCompanyOptions(data[i].children, newArr)
        }
      }
    },
    /**
     * @method 全选公司
     */
    choiceAllCompanyItem (val) {
      let { companyResult } = this
      // true = 添加  false 取消、减少
      let rType = val.length > this.form.copyCompanyId.length
      let firstVal = val[0] && val[0][0]
      if (rType) {
        // 添加
        if (firstVal && val.length === companyResult.length) {
          // 其他都选完了，就只有全选没选了
          this.subForm.company = [[0], ...val]
        } else if (firstVal === 0) {
          this.subForm.company = [[0], ...companyResult]
        }
      } else {
        // 减少
        if (firstVal === 0) {
          // 第一个为0 只取消全选
          let copyArr = JSON.parse(JSON.stringify(val))
          copyArr.splice(0, 1)
          this.subForm.company = copyArr
        } else if (val.length === companyResult.length) {
          // 清空
          this.subForm.company = []
        } else {
          this.subForm.company = val
        }
      }
      this.form.copyCompanyId = this.subForm.company
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    getCover (imgs) {
      this.subForm.cover = imgs
    },
    handleMomentTime (time) {
      return new Date(time * 1000)
    },
    handleTimes (time) {
      return parseInt(new Date(time).getTime() / 1000)
    },
    goBack () {
      this.$router.back(-1)
    },
    async submitFormInfo () {
      let form = JSON.parse(JSON.stringify(this.form))
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      let formArr = ['timeForm', 'aForm', 'bForm', 'cForm', 'dForm']
      formArr.push(subForm.out_type === 1 ? 'outTimeForm' : 'outDayForm')
      formArr.push(subForm.user_out_type === 1 ? 'userOutTimeForm' : 'userOutDayForm')
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        subForm.imgs = subForm.imgs.map(item => {
          return item.url
        })
        this.authList.map(item => {
          subForm[item.key] = 0
          this.checkList.map(aitem => {
            if (item.title === aitem) {
              subForm[item.key] = 1
            }
          })
        })
        if (subForm.company[0][0] === 0) {
          subForm.company.splice(0, 1)
        }
        subForm.start_time = this.handleTimes(form.time[0]) || ''
        subForm.end_time = this.handleTimes(form.time[1]) || ''
        subForm.coupon_start = subForm.out_type === 1 ? this.handleTimes(form.out_time[0]) : ''
        subForm.coupon_end = subForm.out_type === 1 ? this.handleTimes(form.out_time[1]) : ''
        subForm.user_coupon_start = subForm.user_out_type === 1 ? this.handleTimes(form.user_out_time[0]) : ''
        subForm.user_coupon_end = subForm.user_out_type === 1 ? this.handleTimes(form.user_out_time[1]) : ''
        subForm.cover = subForm.cover[0].url
        let method = subForm.id ? 'presentActiveUpdate' : 'presentActiveAdd'
        let { code } = await this.$api[method](subForm)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.goBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-edit-card {
  width: 100%;
  .el-input,
  .el-select,
  .lb-input-number,
  .el-cascader {
    width: 400px;
  }
}
</style>
